function getLocalFilePath(path: string): string {
  // 提前定义常见的本地路径前缀
  const localPrefixes = ['_www', '_doc', '_documents', '_downloads']

  // 检查是否已经是本地路径格式
  if (localPrefixes.some(prefix => path.startsWith(prefix))
    || path.startsWith('file://')
    || path.startsWith('/storage/emulated/0/')) {
    return path
  }

  // 处理绝对路径
  if (path.startsWith('/')) {
    try {
      const localFilePath = plus.io.convertAbsoluteFileSystem(path)
      return localFilePath !== path ? localFilePath : `_www/${path.substring(1)}`
    }
    catch (e) {
      // 如果转换失败，回退到原来的逻辑
      return `_www/${path.substring(1)}`
    }
  }

  // 默认情况
  return `_www/${path}`
}

let index = 0
function getNewFileId() {
  return Date.now() + String(index++)
}

function biggerThan(v1: string, v2: string) {
  const v1Array = v1.split('.')
  const v2Array = v2.split('.')
  let update = false
  for (let index = 0; index < v2Array.length; index++) {
    const diff = Number(v1Array[index]) - Number(v2Array[index])
    if (diff !== 0) {
      update = diff > 0
      break
    }
  }
  return update
}

export function pathToBase64(path: string) {
  return new Promise((resolve, reject) => {
    if (typeof window === 'object' && 'document' in window) {
      if (typeof FileReader === 'function') {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', path, true)
        xhr.responseType = 'blob'
        xhr.onload = function () {
          if (this.status === 200) {
            const fileReader = new FileReader()
            fileReader.onload = function (e) {
              resolve(e.target.result)
            }
            fileReader.onerror = reject
            fileReader.readAsDataURL(this.response)
          }
        }
        xhr.onerror = reject
        xhr.send()
        return
      }
      const canvas = document.createElement('canvas')
      const c2x = canvas.getContext('2d')
      const img = new Image()
      img.onload = function () {
        canvas.width = img.width
        canvas.height = img.height
        c2x!.drawImage(img, 0, 0)
        resolve(canvas.toDataURL())
        canvas.height = canvas.width = 0
      }
      img.onerror = reject
      img.src = path
    }
    else if (typeof plus === 'object') {
      plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), (entry) => {
        entry.file((file) => {
          const fileReader = new plus.io.FileReader()
          fileReader.onload = function (data) {
            resolve(data.target.result)
          }
          fileReader.onerror = reject
          fileReader.readAsDataURL(file)
        }, reject)
      }, reject)
    }
    else if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
      wx.getFileSystemManager().readFile({
        filePath: path,
        encoding: 'base64',
        success(res) {
          resolve(`data:image/png;base64,${res.data}`)
        },
        fail: reject
      })
      return
    }
    reject(new Error('not support'))
  })
}

export function base64ToPath(base64: string) {
  return new Promise((resolve, reject) => {
    if (typeof window === 'object' && 'document' in window) {
      const [header, body] = base64.split(',')
      const type = header.match(/:(.*?);/)?.[1]
      const str = atob(body)
      let n = str.length
      const array = new Uint8Array(n)
      while (n--) {
        array[n] = str.charCodeAt(n)
      }
      return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type })))
    }
    let extName = base64.match(/data:\S+\/(\S+);/)
    if (extName) {
      extName = extName[1]
    }
    else {
      reject(new Error('base64 error'))
    }
    const fileName = `${getNewFileId()}.${extName}`
    if (typeof plus === 'object') {
      const basePath = '_doc'
      const dirPath = 'uniapp_temp'
      const filePath = `${basePath}/${dirPath}/${fileName}`
      if (!biggerThan(plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472', plus.runtime.innerVersion)) {
        plus.io.resolveLocalFileSystemURL(basePath, (entry) => {
          entry.getDirectory(dirPath, {
            create: true,
            exclusive: false,
          }, (entry) => {
            entry.getFile(fileName, {
              create: true,
              exclusive: false,
            }, (entry) => {
              entry.createWriter((writer) => {
                writer.onwrite = function () {
                  resolve(filePath)
                }
                writer.onerror = reject
                writer.seek(0)
                writer.writeAsBinary(base64.replace(/^data:\S[^\s/]*\/\S+;base64,/, ''))
              }, reject)
            }, reject)
          }, reject)
        }, reject)
        return
      }
      const bitmap = new plus.nativeObj.Bitmap(fileName)
      bitmap.loadBase64Data(base64, () => {
        bitmap.save(filePath, {}, () => {
          bitmap.clear()
          resolve(filePath)
        }, (error) => {
          bitmap.clear()
          reject(error)
        })
      }, (error) => {
        bitmap.clear()
        reject(error)
      })
      return
    }
    if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
      const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`
      wx.getFileSystemManager().writeFile({
        filePath,
        data: base64.replace(/^data:\S[^\s/]*\/\S+;base64,/, ''),
        encoding: 'base64',
        success() {
          resolve(filePath)
        },
        fail(error) {
          reject(error)
        }
      })
      return
    }
    reject(new Error('not support'))
  })
}
